import axios from "axios";
import { Message } from "element-ui";
import { getToken, removeToken } from "@/utils/auth.js";

export default function fetch(options) {
  // 时间戳
  const timestamp = new Date().getTime();
  return new Promise((resolve, reject) => {
    const instance = axios.create({
      // baseURL: process.env.VUE_APP_apiUrl,
      baseURL: "/api",
      timeout: 30000,
      headers: {
        "Content-Type": "application/json",
      }
    });

    // http request 拦截器
    instance.interceptors.request.use(
      (config) => {
        if (getToken()) {
          config.headers["Authorization"] = getToken();
        }
        return config;
      },
      (err) => {
        console.log("-------", err);
        return Promise.reject(err);
      }
    );

    // http response 拦截器
    instance.interceptors.response.use(
      (response) => {
        return response;
      },
      (error) => {
        console.dir(error)
        console.dir(error.message, "error");
        if (error) {
          if (error.response == null) {
            console.log("提示：后台无响应");
          } else {
            switch (error.response.status) {
              case 401:
                localStorage.removeItem("token");
                localStorage.clear();
                location.href = "/login";
                break;
              case 500:
                console.log(error);
                Message.error(error.response.data.msg||error.message);
                break;
            }
          }
        }
        return Promise.reject(error);
      }
    );

    // 请求处理
    instance(options)
      .then((res) => {
        console.log("请求配置", options);
        console.log("请求响应---\r\n", res.data);
        resolve(res.data);
      })
      .catch((error) => {
        if (error.response.status === 500) {
          if(error.response.data.code===401){
            localStorage.removeItem("token");
            localStorage.clear();
            location.href = "/login";
          }
          if(error.response.data.message){
            Message.error(error.response.data.message);
          }
          Message.error(error.response.statusText);
        } else {
          Message.error(error.response.statusText);
        }
        reject(error);
      });
  });
}
